package cn.slipi.admin.config;

import cn.slipi.admin.common.Properties.ZookeeperProperty;
import cn.slipi.admin.common.serializer.ZkSerializerFactory;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.ZkSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ZookeeperConfiguration
 */
@Configuration
public class ZookeeperConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "spring.zookeeper")
    public ZookeeperProperty zookeeperProperty() {
        return new ZookeeperProperty();
    }

    @Bean
    @ConditionalOnMissingBean(value = ZkSerializer.class)
    public ZkSerializer zkSerializer(ZookeeperProperty zookeeperProperty) {
        return ZkSerializerFactory.of(zookeeperProperty.getSerializer());
    }

    @Bean
    public ZkClient zkClient(ZookeeperProperty zookeeperProperty, ZkSerializer zkSerializer) {
        return new ZkClient(zookeeperProperty.getUrl(),
                zookeeperProperty.getSessionTimeout(),
                zookeeperProperty.getConnectionTimeout(),
                zkSerializer);
    }
}
